﻿using System.Globalization;
using System.IO;
using System.Xml.Linq;
using ResxHelper.Object;
using System.Linq;

namespace ResxHelper.Logic.Readers
{
    /// <summary>
    /// Reads android resource files to intermediate object
    /// </summary>
    public class AndroidResourceFileReader : IResourceFileReader
    {
        public string Path { get; private set; }

        public AndroidResourceFileReader(string path)
        {
            Path = path;
        }

        public ResourceFile Read()
        {
            XDocument doc;
            try
            {
                doc = XDocument.Load(Path);
            }
            catch
            {
                throw new FileLoadException(string.Format("{0} could not be read (path={0}) could not be read!", Path));
            }

            return new ResourceFile
            {
                CultureInfo = GetCulture(Path),
                FilePath = Path,
                Entries = GetEntries(doc)
            };
        }

        private static ResourceFileEntryCollection GetEntries(XDocument doc)
        {
            var entries = new ResourceFileEntryCollection();
            var resources = doc.Descendants("string");
            foreach (var resource in resources)
            {
                
                var commentEl = resource.Attribute("comment");
                var exampleEl = resource.Attribute("example");

                var comment = commentEl == null ? string.Empty : commentEl.Value;
                var example = exampleEl == null ? string.Empty : exampleEl.Value;

                var key = resource.Attribute("name").Value;
                var value = resource.Value;

                entries.Add(key, new ResourceFileEntry{ Key = key, Value = value, Comment = comment, Example = example });
            }
            return entries;
        }

        private static CultureInfo GetCulture(string path)
        {
            // scope/res/values-local/string.xml
            var pathSplit = path.Split('\\');
            var valuesDirectoryName = pathSplit[pathSplit.Length - 2];

            var dirNameSplit = valuesDirectoryName.Split('-');

            var culture = CultureInfo.InvariantCulture;
            
            if (dirNameSplit.Count() > 1)
                culture = new CultureInfo(dirNameSplit[1]);

            return culture;
        }
    }
}
